<script setup>
import {defineEmits, ref} from 'vue'
import {ElMessage} from 'element-plus'
import * as qiniu from 'qiniu-js'
import {getToken} from '@/api/qiniu.js'; // 获取七牛上传凭证的 API
import {Delete, Plus, ZoomIn} from "@element-plus/icons-vue";

const emit = defineEmits(['list'])
const props = defineProps({
  limit: {
    type: Number,
    required: true
  }
})

const fileList = ref([])

const handleRemove = (uploadFile, uploadFiles) => {
  fileList.value = uploadFiles
}

const handlePreview = (file) => {
  console.log('预览文件:', file)
}

const handleOnChange = (uploadFile, uploadFiles) => {
  if (uploadFile.status !== 'ready') return
  const rawFile = uploadFile.raw

  // ✅ 判断是否是图片类型
  const isImage = rawFile.type.startsWith('image/')
  if (!isImage) {
    ElMessage.warning('只能上传图片类型文件')
    // 移除这个不是图片的文件
    fileList.value = uploadFiles.filter(file => file.uid !== uploadFile.uid)
    return
  }

  // ✅ 重复文件检测
  const isDuplicate = uploadFiles.slice(0, -1).some(file =>
      file.name === rawFile.name && file.raw?.size === rawFile.size
  )

  if (isDuplicate) {
    ElMessage.warning('该图片已选择，请勿重复上传')
    fileList.value = uploadFiles.slice(0, -1)
  }

  fileList.value = [...uploadFiles]  // ✅ 手动同步 fileList
  emit('list', fileList.value)
}


const dialogVisible = ref(false)
const dialogImageUrl = ref('')
const disabled = ref(false)
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true
}

const clear = () => {
  fileList.value = []
}

// 让父组件可以调用这个方法
defineExpose({
  clear
})
</script>

<template>
  <el-upload
      class="upload-demo"
      :auto-upload="false"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-change="handleOnChange"
      v-model:file-list="fileList"
      list-type="picture-card"
      multiple
      :limit="props.limit"
  >
    <el-icon>
      <Plus/>
    </el-icon>
    <template #file="{ file }">
      <div>
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt=""/>
        <span class="el-upload-list__item-actions">
          <span
              class="el-upload-list__item-preview"
              @click="handlePictureCardPreview(file)"
          >
            <el-icon><zoom-in/></el-icon>
          </span>
          <span
              v-if="!disabled"
              class="el-upload-list__item-delete"
              @click="handleRemove"
          >
            <el-icon><Delete/></el-icon>
          </span>
        </span>
      </div>
    </template>
  </el-upload>
  <el-dialog v-model="dialogVisible">
    <img style="width: 100%;" :src="dialogImageUrl" alt="Preview Image"/>
  </el-dialog>
</template>
